package lc.q1_50;


public class Q29 {

    public int divide(int dividend, int divisor) {
        // 先考虑将dividend分解成每一位？
        if (divisor == 0) {
            throw new RuntimeException("不能被0除");
        }
        if (dividend == 0) {
            return 0;
        }
        // 溢出的方式只有Int.max / -1
        if (dividend == Integer.MIN_VALUE && divisor == -1) {
            return Integer.MAX_VALUE;
        }
        return times(dividend,divisor);
    }

    int times(long dividend, long divisor) {
        // 如何变成循环呢
        long remain = dividend;
        int times = 0;
        int total = 0;
        if (
                (remain < divisor && remain > 0) ||
                        (remain > divisor && remain < 0)
                        || (remain > 0 && divisor < 0 && remain + divisor < 0)
                        || (remain < 0 && divisor > 0 && remain + divisor > 0)
        ) {
            return 0;
        }
        // 改变一下，假设条件
        while (true) {
            long next = divisor;
            if (remain > 0) {
                if (next > 0) {
                    times = 1;
                    // 这里可能会溢出，需要考虑下
                    while (remain - next - next > 0) {
                        next += next;
                        times += times;
                    }
                    if (remain - next >= 0) {
                        total += times;
                    }
                    remain = remain - next;
                } else {
                    times = -1;
                    while (remain + next + next > 0) {
                        next += next;
                        times += times;
                    }
                    if (remain + next >= 0) {
                        total += times;
                    }
                    remain = remain + next;
                }
                if (remain <= 0) {
                    break;
                }
            } else {
                if (next > 0) {
                    times = -1;
                    while (remain + next + next < 0) {
                        next += next;
                        times += times;
                    }
                    if (remain + next <= 0) {
                        total += times;
                    }
                    remain = remain + next;
                } else {
                    times = 1;
                    while (remain - next - next < 0) {
                        next += next;
                        times += times;
                    }
                    if (remain - next <= 0) {
                        total += times;
                    }
                    remain = remain - next;
                }
                if (remain >= 0) {
                    break;
                }
            }
        }

        return total;

    }



    public static void main(String[] args) {
        System.out.println(new Q29().divide(1100540749,-1090366779));
        System.out.println(Integer.MIN_VALUE / 3);
    }

}
